<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/13
 * Time: 17:40
 */

namespace Admin\Controller;
use Admin\Model\AuthGroupModel;
use Think\Model;

Vendor("pdf.tcpdf");
class OrderController extends AdminController{
    //文档分类id
    private $cate_id  =  null;
    /**
     * 分类工单列表页
     * @param integer $cate_id 分类id
     * @param integer $model_id 模型id
     * @param integer $position 推荐标志
     * @param integer $group_id 分组id
     */
    public function index($cate_id = null, $model_id = null, $position = null,$group_id=null){
        //获取左边菜单
        $this->getMenu();

        if($cate_id===null){
            $cate_id = $this->cate_id;
        }
        if(!empty($cate_id)){
            $pid = I('pid',0);
            // 获取列表绑定的模型
            if ($pid == 0) {
                $models     =   get_category($cate_id, 'model');
                // 获取分组定义
                $groups		=	get_category($cate_id, 'groups');
                if($groups){
                    $groups	=	parse_field_attr($groups);
                }
            }else{ // 子文档列表
                $models     =   get_category($cate_id, 'model_sub');
            }
            if(is_null($model_id) && !is_numeric($models)){
                // 绑定多个模型 取基础模型的列表定义
                $model = M('Model')->getByName('order');
            }else{
                $model_id   =   $model_id ? : $models;
                //获取模型信息
                $model = M('Model')->getById($model_id);
                if (empty($model['list_grid'])) {
                    $model['list_grid'] = M('Model')->getFieldByName('order','list_grid');
                }
            }
            $this->assign('model', explode(',', $models));
        }else{
            // 获取基础模型信息
            $model = M('Model')->getByName('order');
            $model_id   =   null;
            $cate_id    =   0;
            $this->assign('model', null);
        }

        //解析列表规则
        $fields =	array();
        $grids  =	preg_split('/[;\r\n]+/s', trim($model['list_grid']));
        foreach ($grids as &$value) {
            // 字段:标题:链接
            $val      = explode(':', $value);
            // 支持多个字段显示
            $field   = explode(',', $val[0]);
            $value    = array('field' => $field, 'title' => $val[1]);
            if(isset($val[2])){
                // 链接信息
                $value['href']  =   $val[2];
                // 搜索链接信息中的字段信息
                preg_replace_callback('/\[([a-z_]+)\]/', function($match) use(&$fields){$fields[]=$match[1];}, $value['href']);
            }
            if(strpos($val[1],'|')){
                // 显示格式定义
                list($value['title'],$value['format'])    =   explode('|',$val[1]);
            }
            foreach($field as $val){
                $array  =   explode('|',$val);
                $fields[] = $array[0];
            }
        }

        // 文档模型列表始终要获取的数据字段 用于其他用途
        $fields[] = 'category_id';
        $fields[] = 'model_id';
        $fields[] = 'pid';
        // 过滤重复字段信息
        $fields =   array_unique($fields);
        // 列表查询
        $list   =   $this->getOrderList($cate_id,$model_id,$position,$fields,$group_id);
        // 列表显示处理
        $list   =   $this->parseOrderList($list,$model_id);

        $this->assign('model_id',$model_id);
        $this->assign('group_id',$group_id);
        $this->assign('position',$position);
        $this->assign('groups', $groups);
        $this->assign('list',   $list);
        $this->assign('list_grids', $grids);
        $this->assign('model_list', $model);
        //内容高亮
        $this->assign('current', 1);
        // 记录当前列表页的cookie
        Cookie('__forward__',$_SERVER['REQUEST_URI']);
        $this->display();
    }

    /**
     * 文档新增页面初始化
     * @author huajie <banhuajie@163.com>
     */
    public function add(){
        //获取左边菜单
        $this->getMenu();

        $cate_id    =   I('get.cate_id',0);
        $model_id   =   I('get.model_id',0);
        $group_id	=	I('get.group_id','');

        empty($cate_id) && $this->error('参数不能为空！');
        empty($model_id) && $this->error('该分类未绑定模型！');

        //检查该分类是否允许发布
        $allow_publish = check_category($cate_id);
        !$allow_publish && $this->error('该分类不允许发布内容！');

        // 获取当前的模型信息
        $model    =   get_order_model($model_id);

        //处理结果
        $info['pid']            =   $_GET['pid']?$_GET['pid']:0;
        $info['model_id']       =   $model_id;
        $info['category_id']    =   $cate_id;
        $info['group_id']		=	$group_id;

        if($info['pid']){
            // 获取上级文档
            $order            =   M('Order')->field('id,title,type')->find($info['pid']);
            $this->assign('order',$order);
        }

        //获取表单字段排序
        $fields = get_model_attribute($model['id']);
        $this->assign('info',       $info);
        $this->assign('fields',     $fields);
        $this->assign('type_list',  get_type_bycate($cate_id));
        $this->assign('model',      $model);
        $this->meta_title = '新增'.$model['title'];
        //内容高亮
        $this->assign('current', 1);
        $this->display();
    }

    /**
     * 更新一条数据
     * @author huajie <banhuajie@163.com>
     */
    public function update(){
        $order   =   D('Order');
        $res = $order->update();
        if(!$res){
            $this->error($order->getError());
        }else{
            $this->success($res['id']?'更新成功':'新增成功', Cookie('__forward__'));
        }
    }

    /**
     * 文档编辑页面初始化
     * @author huajie <banhuajie@163.com>
     */
    public function edit(){
        //获取左边菜单
        $this->getMenu();

        $id     =   I('get.id','');
        if(empty($id)){
            $this->error('参数不能为空！');
        }

        // 获取详细数据
        $Order = D('Order');
        $data = $Order->detail($id);
        if(!$data){
            $this->error($Order->getError());
        }

        if($data['pid']){
            // 获取上级文档
            $order        =   $Order->field('id,title,type')->find($data['pid']);
            $this->assign('order',$order);
        }
        // 获取当前的模型信息
        $model    =   get_order_model($data['model_id']);

        $this->assign('data', $data);
        $this->assign('model_id', $data['model_id']);
        $this->assign('model',      $model);

        //获取表单字段排序
        $fields = get_model_attribute($model['id']);
        $this->assign('fields',     $fields);


        //获取当前分类的文档类型
        $this->assign('type_list', get_type_bycate($data['category_id']));

        $this->meta_title   =   '编辑工单';
        $this->display();
    }

    /**
     * 设置一条或者多条数据的状态
     */
    public function setStatus($Model=CONTROLLER_NAME){

        $ids    =   I('request.ids');
        $status =   I('request.status');
        if(empty($ids)){
            $this->error('请选择要操作的数据');
        }

        $map['id'] = array('in',$ids);
        switch ($status){
            case -1 :
                $this->delete($Model, $map, array('success'=>'删除成功','error'=>'删除失败'));
                break;
            case 0  :
                $this->forbid($Model, $map, array('success'=>'禁用成功','error'=>'禁用失败'));
                break;
            case 1  :
                $this->resume($Model, $map, array('success'=>'启用成功','error'=>'启用失败'));
                break;
            default :
                $this->error('参数错误');
                break;
        }
    }

    /**
     * 下载某一条工单
     */
    public function download(){
        $id = I('get.id');
        $result = M('Order')->WHERE(array("id"=>$id))->field("customer,repair_type,repair_model,repair_date")->limit(1)->select();
        $info = $result[0];
        $filename = $info['customer'].'工单';
        header("Content-type: application/vnd.ms-excel; charset=utf-8");
        header("Content-Disposition: attachment; filename=$filename.xlsx");
        $data = '工单明细' . "\t\n";
        $data .= '姓名' . "\t" . '设备型号' . "\t" . '送修日期' . "\t\n";
        $data .= $info['customer'] . "\t" . $info['repair_model'] . "\t" . date("Y-m-d",$info['repair_date']);
        echo $data. "\t";
    }

    /**
     * 用pdf格式查看某一条工单
     */
    public function pdf(){
        //获取用户信息
        $id = I('get.id');
        $order = M('Order')->WHERE(array("id"=>$id))->field("customer,repair_model,repair_date,troubles")->limit(1)->select();
        $order_info = $order[0];
        $order_shop = M('Order_shop')->WHERE(array("id"=>$id))->field("repair_price,repair_handsel")->limit(1)->select();
        $order_shop_info=$order_shop[0];
        //实例化
        $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);

// 设置文档信息
        $pdf->SetCreator('ricky');
        $pdf->SetAuthor('ricky');
        $pdf->SetTitle('感谢选择聚宏数码');
        $pdf->SetSubject('');
        $pdf->SetKeywords('TCPDF, PDF, PHP');

// 设置页眉和页脚信息 参数分别是LOGO地址，LOGO大小，两行标题，标题颜色，分割线颜色。。颜色是RGB
        $pdf->SetHeaderData('', '', '', '您的满意就是我们的动力',PDF_HEADER_STRING);
        $pdf->setFooterData(array(0,64,0), array(0,64,128));

// 设置页眉和页脚字体
        $pdf->setHeaderFont(Array('stsongstdlight', '', '10'));
        $pdf->setFooterFont(Array('helvetica', '', '9'));

// 设置默认等宽字体
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// 设置间距
        $pdf->SetMargins(15, 27, 15);
        $pdf->SetHeaderMargin(5);
        $pdf->SetFooterMargin(10);

// 设置分页
        $pdf->SetAutoPageBreak(TRUE, 25);

// 设置图像比例因子
        $pdf->setImageScale(1.25);

// 设置默认字体构造子集模式
        $pdf->setFontSubsetting(true);

// 设置字体
        $pdf->SetFont('stsongstdlight', '', 15);

        $pdf->AddPage();

        $pdf->Cell(0, 5, '聚宏数码回执单', 0, 1, 'C');
        $pdf->Ln(10);
        $pdf->Cell(50, 5, '客户姓名:');
        $pdf->Cell( 80, 5,$order_info['customer']);
        $pdf->Ln(10);
        $pdf->Cell(50, 5, '维修设备型号:');
        $pdf->Cell( 80, 5,$order_info['repair_model']);
        $pdf->Ln(10);
        $pdf->Cell(50, 5, '送修日期:');
        $pdf->Cell( 80, 5,date('Y-m-d',$order_info['repair_date']));
        $pdf->Ln(10);
        $pdf->Cell(50, 5, '故障描述:');
        $pdf->Cell( 80, 5,$order_info['troubles']);
        $pdf->Ln(10);
        $pdf->Cell(50, 5, '接待人:');
        $pdf->Cell( 80, 5,'潘华');
        $pdf->Ln(10);
        $pdf->Cell(50, 5, '维修报价:');
        $pdf->Cell( 80, 5,($order_shop_info['repair_price']?:0).'元');
        $pdf->Ln(10);
        $pdf->Cell(50, 5, '已收定金:');
        $pdf->Cell( 80, 5,($order_shop_info['repair_handsel']?:0).'元');
        $pdf->Ln(10);
        /*$str1 = '聚宏数码回执单';
        $pdf->Write(0,$str1,'', 0, 'L', true, 0, false, false, 0);*/

        //输出PDF
        $pdf->Output('test.pdf', 'I');
    }
    /**
     * 写文章时自动保存至草稿箱
     * @author huajie <banhuajie@163.com>
     */
    public function autoSave(){
        $res = D('Order')->autoSave();
        if($res !== false){
            $return['data']     =   $res;
            $return['info']     =   '保存草稿成功';
            $return['status']   =   1;
            $this->ajaxReturn($return);
        }else{
            $this->error('保存草稿失败：'.D('Order')->getError());
        }
    }

    /**
     * 显示左边菜单，进行权限控制
     * @author huajie <banhuajie@163.com>
     */
    protected function getMenu(){
        //获取动态分类
        $cate_auth  =   AuthGroupModel::getAuthCategories(UID); //获取当前用户所有的内容权限节点
        $cate_auth  =   $cate_auth == null ? array() : $cate_auth;
        $cate       =   M('Category')->where(array('status'=>1))->field('id,title,pid,allow_publish,model_id')->order('pid,sort')->select();

        //没有权限的分类则不显示
        if(!IS_ROOT){
            foreach ($cate as $key=>$value){
                if(!in_array($value['id'], $cate_auth)){
                    unset($cate[$key]);
                }
            }
        }

        $cate           =   list_to_tree($cate);    //生成分类树

        //获取分类id
        $cate_id        =   I('param.cate_id');
        $this->cate_id  =   $cate_id;

        //是否展开分类
        $hide_cate = false;
        if(ACTION_NAME != 'recycle' && ACTION_NAME != 'draftbox' && ACTION_NAME != 'mydocument'){
            $hide_cate  =   true;
        }

        //生成每个分类的url
        foreach ($cate as $key=>&$value){
            if($cate_id == $value['id'] && $hide_cate){
                $value['current'] = true;
            }else{
                $value['current'] = false;
            }
            if($value['model_id']==4) {
                $value['url'] = 'Order/index?cate_id=' . $value['id'];
                if (!empty($value['_child'])) {
                    $is_child = false;
                    foreach ($value['_child'] as $ka => &$va) {
                        $va['url'] = 'Order/index?cate_id=' . $va['id'];
                        if (!empty($va['_child'])) {
                            foreach ($va['_child'] as $k => &$v) {
                                $v['url'] = 'Order/index?cate_id=' . $v['id'];
                                $v['pid'] = $va['id'];
                                $is_child = $v['id'] == $cate_id ? true : false;
                            }
                        }
                        //展开子分类的父分类
                        if ($va['id'] == $cate_id || $is_child) {
                            $is_child = false;
                            if ($hide_cate) {
                                $value['current'] = true;
                                $va['current'] = true;
                            } else {
                                $value['current'] = false;
                                $va['current'] = false;
                            }
                        } else {
                            $va['current'] = false;
                        }
                    }
                }
            }else{
                //父类地址
                $value['url']   =   'Article/index?cate_id='.$value['id'];
                //子类地址
                if(!empty($value['_child'])){
                    $is_child = false;
                    foreach ($value['_child'] as $ka=>&$va){
                        $va['url']      =   'Article/index?cate_id='.$va['id'];
                        if(!empty($va['_child'])){
                            foreach ($va['_child'] as $k=>&$v){
                                $v['url']   =   'Article/index?cate_id='.$v['id'];
                                $v['pid']   =   $va['id'];
                                $is_child = $v['id'] == $cate_id ? true : false;
                            }
                        }
                        //展开子分类的父分类
                        if($va['id'] == $cate_id || $is_child){
                            $is_child = false;
                            if($hide_cate){
                                $value['current']   =   true;
                                $va['current']      =   true;
                            }else{
                                $value['current']   =   false;
                                $va['current']      =   false;
                            }
                        }else{
                            $va['current']      =   false;
                        }
                    }
                }
            }
        }
        $this->assign('nodes',      $cate);
        $this->assign('cate_id',    $this->cate_id);

        //获取面包屑信息
        $nav = get_parent_category($cate_id);
        $this->assign('rightNav',   $nav);

        //获取回收站权限
        $this->assign('show_recycle', IS_ROOT || $this->checkRule('Admin/article/recycle'));
        //获取草稿箱权限
        $this->assign('show_draftbox', C('OPEN_DRAFTBOX'));
        //获取审核列表权限
        $this->assign('show_examine', IS_ROOT || $this->checkRule('Admin/article/examine'));
    }

    /**
     * 默认工单列表方法
     * @param integer $cate_id 分类id
     * @param integer $model_id 模型id
     * @param integer $position 推荐标志
     * @param mixed $field 字段列表
     * @param integer $group_id 分组id
     */
    protected function getOrderList($cate_id=0,$model_id=null,$position=null,$field=true,$group_id=null){
        /* 查询条件初始化 */
        $map = array();
        if(isset($_GET['phone'])){
            $map['phone']  = array('like', '%'.(string)I('phone').'%');
        }
        if(isset($_GET['status'])){
            $map['status'] = I('status');
            $status = $map['status'];
        }else{
            $status = null;
            $map['status'] = array('in', '0,1,2');
        }
        if(isset($_GET['repair_status'])){
            $map['repair_status'] = I('repair_status');
            $repair_status = $map['repair_status'];
        }else{
            $map['repair_status'] = array('in', '1,2,3');
        }
        if ( isset($_GET['time-start']) ) {
            $map['repair_date'][] = array('egt',strtotime(I('time-start')));
        }
        if ( isset($_GET['time-end']) ) {
            $map['repair_date'][] = array('elt',24*60*60-1 + strtotime(I('time-end')));
        }
        if ( isset($_GET['customer']) ) {
            $map['customer'] = I('customer');
        }

        // 构建列表数据
        $Order = M('Order');

        if($cate_id){
            $map['category_id'] =   $cate_id;
        }
        $map['pid']         =   I('pid',0);
        if($map['pid']){ // 子文档列表忽略分类
            unset($map['category_id']);
        }
        $Order->alias('ORDERS');
        if(!is_null($model_id)){
            $map['model_id']    =   $model_id;
            if(is_array($field) && array_diff($Order->getDbFields(),$field)){
                $modelName  =   M('Model')->getFieldById($model_id,'name');
                $Order->join('__ORDER_'.strtoupper($modelName).'__ '.$modelName.' ON ORDERS.id='.$modelName.'.id');
                $key = array_search('id',$field);
                if(false  !== $key){
                    unset($field[$key]);
                    $field[] = 'ORDERS.id';
                }
            }
        }
        /*点位 组别为空*/
        if(!is_null($position)){
            $map[] = "position & {$position} = {$position}";
        }
        if(!is_null($group_id)){
            $map['group_id']	=	$group_id;
        }
        /*end*/

        $list = $this->lists($Order,$map,'ORDERS.id DESC',$field);

        if($map['pid']){
            // 获取上级文档
            $order    =   $Order->field('id,title,type')->find($map['pid']);
            $this->assign('order',$order);
        }
        //检查该分类是否允许发布内容
        $allow_publish  =   get_category($cate_id, 'allow_publish');

        $this->assign('repair_status', $repair_status);
        $this->assign('allow',  $allow_publish);
        $this->assign('pid',    $map['pid']);

        $this->meta_title = '工单列表';
        return $list;
    }

}